<template>
  <a-modal
    :visible="visible"
    title="退款"
    :maskClosable="false"
    @cancel="closeModal"
    @ok="handleSubmit"
    :confirmLoading="submitLoading"
    :width="1000"
    :okText="haveApprove ? '保存&发起审批' : '保存'"
    :destroyOnClose="true"
  >
    <div class="carry-content beauty-scroller-bar">

      <a-alert type="info" v-if="!haveApprove">
        <template #message>
          调整金暂未开启审批，如需开启审批，请前往”财务-所有账单-更多-审批配置“中设置，点击”<span
          class="link"
          @click.stop="goSetting"
        >配置</span
        >“可快速设置。
        </template>
      </a-alert>

      <CustomTable
        titleName="退款列表"
        ref="customTable"
        :requestInfo="requestInfo"
        :hasPagination="false"
        :extraParams="extraParams"
        :hasMoreAction="false"
        :columns="columns"
        @request="$utils.commonRequest"
        :tableConfig="$store.getters.tableConfig"
        :tableHeight="400"
        @getListResult="getListResult"
      >
        <template #column-needRefund="{ record, text }">
          <a-input-number
            v-if="!record.isLast"
            v-model:value="record.needRefund"
            :min="0"
            :precision="2"
            :max="Number(record?.actual_payment || 0)"
            style="width: 100%"
          />
          <span v-else>合计：{{text}}</span>
        </template>
        <template #column-needRefundReason="{ record }">
          <a-textarea
            v-if="!record.isLast"
            v-model:value="record.needRefundReason"
            style="width: 100%"
            placeholder="请输入退款原因"
            :auto-size="{ minRows: 1, maxRows: 3 }"
          />
        </template>
      </CustomTable>
    </div>

    <!--  审批配置  -->
    <BillApprovalSetting
      :visible="approvalVisible"
      @closeModal="closeApproval"
    />

  </a-modal>
</template>

<script>
import {defineComponent, reactive, toRefs, computed, watch, ref, createVNode} from "vue";
import {Form, message, TreeSelect, Modal} from "ant-design-vue";
import request from "@/common/utils/request";
import _ from "lodash";
import BLCOMMON from "bl-common-vue3";
import utils from "@/common/utils/utils";
import { CustomTable } from "bl-common-vue3";
import BillApprovalSetting from "@/components/contract/CustomFilter/modules/BillApprovalSetting.vue";
import {ExclamationCircleOutlined} from "@ant-design/icons-vue";
export default defineComponent({
  name: "BillRefundModal",
  components: {
    BillApprovalSetting,
    CustomTable,
  },
  props: {
    // 打开弹框
    visible: {
      type: Boolean,
      default: false,
    },
    billIds: {
      type: Array,
      default: () => [],
    },
  },

  setup(props, { emit }) {
    const state = reactive({
      requestInfo: {
        service: '/org', // 请求服务
        serviceUrl: '/bill/list', // 请求url
        serviceType: 'post', // 请求方式
      },
      customTable: null,
      dataSource: [],
      submitLoading: false,
      haveApprove: false,
      approvalVisible: false,
    });


    const extraParams = computed(() => {
      return {billIds: props.billIds, isRefund: 1, page: 1, limit: props.billIds?.length < 999 ? 999 : props.billIds?.length}
    });

    const truthSourceData = computed(() => {
      return state.dataSource.filter((v) => !v.isLast)
    });

    const receivablePaymentTotal = computed(() => {
      return truthSourceData.value.reduce((acc, cur) => utils.countSum([acc, Number(cur.receivable_payment)]), 0);
    });

    const actualPaymentTotal = computed(() => {
      return truthSourceData.value.reduce((acc, cur) => utils.countSum([acc, Number(cur.actual_payment)]), 0);
    });

    const refundTotal = computed(() => {
      return truthSourceData.value.reduce((acc, cur) => utils.countSum([acc, Number(cur.needRefund)]), 0);
    });

    const closeModal = () => {
      emit("handleClose");
    };

    const getListResult = (res) => {
      state.dataSource = res?.list || [];
      if (res?.list?.length) {
        state.dataSource.push({
          isLast: 1,
          receivable_payment: receivablePaymentTotal.value,
          actual_payment: actualPaymentTotal.value,
          needRefund: refundTotal.value,
        })
      }
    };

    watch(
      [() => receivablePaymentTotal.value, () => actualPaymentTotal.value,() => refundTotal.value],
      () => {
        state.dataSource.forEach((v) => {
          if (v.isLast == 1) {
            v.receivable_payment = receivablePaymentTotal.value;
            v.actual_payment = actualPaymentTotal.value;
            v.needRefund = refundTotal.value;
          }
        })
      }
    );

    const handleSubmit = () => {
      if (Number(refundTotal.value)) {
        let submitArr = _.cloneDeep(truthSourceData.value).filter((v) => v.needRefund)?.map((v) => {
          return {
            bill_id: v.id,
            amount: v.needRefund,
            remark: v.needRefundReason,
          }
        });
        state.submitLoading = true;
        request.post("/org", "/newBill/refundBill", {
          refundData: submitArr,
          needMsg: true,
        }).then((res) => {
          message.success(res.msg || "保存成功！");
          emit("handleSuccess");
        }).catch((err) => {
          if (err.code == 12001) {
            Modal.confirm({
              title: () => "提示",
              content: () =>
                err?.msg || "您需要先设置调整审批流程才能调整金额哦~",
              icon: () => createVNode(ExclamationCircleOutlined),
              centered: true,
              okText: () => "前往",
              onOk() {
                emit("handleClose");
                if (window.__MICRO_APP_ENVIRONMENT__) {
                  window.microApp.forceDispatch({
                    type: "SetMicroPages",
                    microInfo: {
                      microId: `org_workApproval_manage_index`,
                      app: 'workApproval',
                      name: '管理审批',
                      url: `/approval/manage/index`,
                    }
                  })
                }
              },
            });
          }
        }).finally(() => {
          state.submitLoading = false;
        })
      } else {
        message.warn('请先填写退款金额再进行保存操作')
      }
    };

    const getSetting = () => {
      // 获取配置
      request.get("/org", "/bill/approvalGet").then((res) => {
        state.haveApprove = !!res?.config?.find(
          (v) => v.type === "adjust_approve"
        )?.is_use;
      });
    };

    const goSetting = () => {
      state.approvalVisible = true;
    };

    const closeApproval = () => {
      state.approvalVisible = false;
      getSetting();
    };

    const init = () => {
      getSetting();
    };
    const reset = () => {
      state.dataSource = [];
      state.haveApprove = false;
      state.submitLoading = false;
    };


    watch(
      () => props.visible,
      (visible) => {
        if (visible) {
          init();
        } else {
          reset();
        }
      }
    );



    return {
      ...toRefs(state),
      extraParams,
      columns,
      receivablePaymentTotal,
      actualPaymentTotal,
      refundTotal,
      closeModal,
      getListResult,
      handleSubmit,
      closeApproval,
      goSetting,
    };
  },
});
const columns = [
  {
    title: "费用类型",
    dataIndex: "cost_type_txt",
    key: "cost_type_txt",
    width: 120,
  },
  {
    title: "账单周期",
    dataIndex: "contractOn",
    key: "contractOn",
    customRender: ({ text, record, index }) => {
      return record.isLast ? '' : `${record.start_date} ~ ${record.end_date}`;
    },
  },
  {
    title: "应收金额",
    key: "receivable_payment",
    dataIndex: "receivable_payment",
    width: 140,
    customRender: ({ text, record, index }) => {
      return record.isLast ? `合计：${text}` : text || '--';
    },
  },
  {
    title: "实收金额",
    key: "actual_payment",
    dataIndex: "actual_payment",
    width: 140,
    customRender: ({ text, record, index }) => {
      return record.isLast ? `合计：${text}` : text || '--';
    },
  },
  {
    title: "退款金额",
    dataIndex: "needRefund",
    key: "needRefund",
    width: 140,
  },
  {
    title: "退款原因",
    dataIndex: "needRefundReason",
    key: "needRefundReason",
    width: 220,
  },
]

</script>

<style lang="less" scoped>
.carry-content {
  max-height: calc(80vh - 100px);
  min-height: 300px;
  overflow-y: auto;
}
</style>
